package zhangqi.com.aidlclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import zhangqi.com.aidl.IzqAIDL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText mEtNum1 ;
    private EditText mEtNum2 ;
    private EditText mEtRes ;

    private Button mBtnAdd;
    IzqAIDL izqAIDL;

    private ServiceConnection conn = new ServiceConnection() {
        //绑定服务时调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //它返回的就是我们远程服务的IzqAIDL.Stub对象,就是远程的服务
            izqAIDL = IzqAIDL.Stub.asInterface(service);
        }
        //服务断开时调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            izqAIDL = null;//回收资源
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        //软件一启动就绑定服务
        bindService();
    }

    private void initView(){
        mEtNum1 = (EditText) findViewById(R.id.et_num1);
        mEtNum2 = (EditText) findViewById(R.id.et_num2);
        mEtRes = (EditText) findViewById(R.id.et_res);
        mBtnAdd = (Button) findViewById(R.id.btn_add);

        mBtnAdd.setOnClickListener(this);
    }

    public void bindService(){
        //获取到服务端
        Intent intent =new Intent();
        //（"远程服务包名","远程服务全类名"）
        // 安卓5.0后要求必须显示Intent启动绑定服务
        intent.setComponent(new ComponentName("zhangqi.com.aidl",
                "zhangqi.com.aidl.IRemoteService"));
        bindService(intent,conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        int num1 = Integer.parseInt(mEtNum1.getText().toString());
        int num2 = Integer.parseInt(mEtNum2.getText().toString());
        try {
            Log.i("zhangqi",num1+"-----这是他俩的值--------"+num2);
            int res = izqAIDL.add(num1,num2);
            Log.i("zhangqi",res+"-----这是res的值--------");

            mEtRes.setText(res+"");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }
}
